package com.qfjy.project.oauth;

import com.qfjy.common.utils.redis.SysConfigRedisUtils;
import com.qfjy.project.weixin.main.MenuManager;
import com.qfjy.project.weixin.util.WeixinUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @ClassName WeixinOauthController
 * @Description TODO
 * @Author guoweixin
 * @Date 2022/12/2
 * @Version 1.0
 */
@RequestMapping("weixin")
@Controller
@Slf4j
public class WeixinOauthController {
    /**系统配置 Redis sysconfig*/
    @Autowired
    private SysConfigRedisUtils sysConfigRedisUtils;
    /**
     * 1、引导用户进入授权页面同意授权，获取code
     */
    @GetMapping("oauth")
    public void oauth(HttpServletResponse response) throws Exception {

        String redirect_uri="http://javaqf.natapp1.cc/weixin/invoke";
        redirect_uri=URLEncoder.encode(redirect_uri,"UTF-8");

        String url="https://open.weixin.qq.com/connect/oauth2/authorize?" +
                "appid=" + MenuManager.appId+
                "&redirect_uri=" +redirect_uri+
                "&response_type=code" +
                "&scope=snsapi_userinfo" +
                "&state=java2204" +
                "#wechat_redirect";


        response.sendRedirect(url);
    }
    /**
     * 2、用户同意授权后
     * 如果用户同意授权，页面将跳转至 redirect_uri/?code=CODE&state=STATE。
     */
    @RequestMapping("invoke")
    public String invoke(HttpServletRequest request){
        //code作为换取access_token的票据，每次用户授权带上的 code 将不一样，code只能使用一次，5分钟未被使用自动过期。
        String code=request.getParameter("code");
        String state=request.getParameter("state");
        log.info("code={},state={}",code,state);

        //3带着授权码code 去 认证服务器获取access_token   通过 code 换取网页授权access_token
        String authUrl="https://api.weixin.qq.com/sns/oauth2/access_token?" +
                "appid=" +MenuManager.appId+
                "&secret=" +MenuManager.appSecret+
                "&code=" +code+
                "&grant_type=authorization_code";
        //4、得到accessToken
       JSONObject jsonObject= WeixinUtil.httpRequest(authUrl,"POST",null);
        log.info(jsonObject.toString());

        String accessToken=jsonObject.getString("access_token");
        String openid=jsonObject.getString("openid");

        //5、带着accessToken和openid [拉取用户信息(需 scope 为 snsapi_userinfo)] 去资源服务器 获取个人信息
        /** 资源服务器
         http：GET（请使用 https 协议）：
         https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN
         */

        String resourceUrl="https://api.weixin.qq.com/sns/userinfo?" +
                "access_token=" +accessToken+
                "&openid=" +openid+
                "&lang=zh_CN";
        //6、请求资源服务器 得到个人信息
      JSONObject jsonObject1=  WeixinUtil.httpRequest(resourceUrl,"GET",null);
        request.setAttribute("r",jsonObject1);
        return "Oauth";
    }
}
